<template>
  <div class="tag-viewer">
    <div class="tag-frame-container">
      <iframe 
        :src="tagPageUrl" 
        frameborder="0"
        @load="handleIframeLoad"
        ref="tagFrame"
      ></iframe>
    </div>
    <div v-if="selectedTag" class="selected-tag">
      已选择标签: {{ selectedTag.name }}
    </div>
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'TagViewer',
  data() {
    return {
      tagPageUrl: 'http://localhost:5098/Tag',
      selectedTag: null,
      error: null,
      token: null
    }
  },
  methods: {
    async handleIframeLoad() {
      try {
        const response = await fetch('http://localhost:5098/api/auth/token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify({
            username: 'admin',
            password: '123456'
          }),
          credentials: 'include'
        });

        if (!response.ok) {
          const errorData = await response.text();
          throw new Error(errorData || '认证失败');
        }

        const data = await response.json();
        this.token = data.token;
        
        this.$refs.tagFrame.contentWindow.postMessage({
          type: 'setToken',
          token: this.token
        }, 'http://localhost:5098');

      } catch (err) {
        console.error('认证错误:', err);
        this.error = '加载标签页面失败：' + err.message;
      }
    },
    handleTagMessage(event) {
      if (event.data.type === 'tagSelected') {
        this.selectedTag = event.data.tag;
        this.$emit('tag-selected', event.data.tag);
      }
    }
  },
  mounted() {
    window.addEventListener('message', this.handleTagMessage);
  },
  beforeUnmount() {  // 将 beforeDestroy 改为 beforeUnmount
    window.removeEventListener('message', this.handleTagMessage);
  }
}
</script>

<style scoped>
.error-message {
  margin-top: 10px;
  padding: 10px;
  background: #fce8e6;
  color: #d93025;
  border-radius: 4px;
  border: 1px solid #fad2cf;
}

.tag-viewer {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
}

.tag-frame-container {
  width: 100%;
  height: 400px;
}

.tag-frame-container iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.selected-tag {
  margin-top: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}
</style>